package com.solveit.aps.io.db;

import javax.swing.JOptionPane;

import com.solveit.core.configuration.SystemConfiguration;
import com.solveit.core.db2.annotations.Column;
import com.solveit.core.db2.annotations.Entity;
import com.solveit.core.db2.annotations.Id;
import com.solveit.core.db2.annotations.Table;
import com.solveit.core.db2.query.builder.Query;

public final class DataBaseVersionCheckComponent {
	@Entity
	@Table(name = "database_version")
	private static final class DataBaseVersionEntity {
		public static final int ID = 1;
		public static final int VERSION_NO = 2;
		public static final int MISMATCHMSG = 3;

		@SuppressWarnings("unused")
		@Id(auto = true)
		@Column(name = "id", nullable = false, alias = ID)
		private Integer id;
		
		@Column(name = "version_no", nullable = false, alias = VERSION_NO)
		private String versionNo;
		
		@Column(name = "mismatch_message", nullable = false, alias = MISMATCHMSG)
		private String mismatchMessage;
	}
	
	public DataBaseVersionCheckComponent() {
		try {
			validate();
		} catch (DatabaseVersionException e){
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.OK_OPTION);
			System.exit(1);
		}
	}
	
	public static void validate() throws DatabaseVersionException {
		// There should be only one record in database_version table
		Query.Select sel = new Query.Select(DataBaseVersionEntity.class);
		final DataBaseVersionEntity entity = InternalDbEntityHelper.getInstance().execSingle(sel);
		if (entity == null) {
			throw new DatabaseVersionException("No database version entry found");
		}
		
		// compare version
		final String currentVersion = SystemConfiguration.getInstance().getParameter("Version").trim();
		if (!currentVersion.equals(entity.versionNo.trim())) {
			throw new DatabaseVersionException(entity.mismatchMessage);
		}
	}
}

